package com.face.client.model;

import com.arcsoft.AFR_FSDKLibrary;
import com.arcsoft.AFR_FSDK_FACEMODEL;
import com.arcsoft.ASVLOFFSCREEN;
import com.arcsoft.FaceInfo;
import com.arcsoft.demo.AFRTest;
import com.face.Const;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.FloatByReference;
import com.sun.jna.ptr.PointerByReference;
import com.util.SDKUtils;

public class AFREngine implements Engine {

    private final int size = 40 * 1024 * 1024;

    private static ThreadLocal<Pointer> pEngine = new ThreadLocal<>();
    private static ThreadLocal<Pointer> pMemory = new ThreadLocal<>();

    @Override
    public Pointer get() {
        return get(pEngine);
    }

    @Override
    public Pointer init() {
        System.out.println("初始化FR引擎");
        PointerByReference phFREngine = new PointerByReference();
        Pointer memory = SDKUtils.createMem(size);
        NativeLong ret = AFR_FSDKLibrary.INSTANCE.AFR_FSDK_InitialEngine(Const.APPID,
                Const.FR_SDKKEY, memory, size,
                phFREngine);
        if (ifError(memory, ret)) {
            System.err.println("FR引擎初始化异常");
        }
        Pointer engine = phFREngine.getValue();
        pEngine.set(engine);
        pMemory.set(memory);
        return engine;
    }

    @Override
    public void destroy() {
        destroy(pEngine, pMemory);
    }

    @Override
    public void release(Pointer engine) {
        AFR_FSDKLibrary.INSTANCE.AFR_FSDK_UninitialEngine(engine);
    }

    public AFR_FSDK_FACEMODEL extractFRFeature(ASVLOFFSCREEN inputImg, FaceInfo faceInfo) {
        return AFRTest.extractFRFeature(get(), inputImg, faceInfo);
    }

    public float faceMatching(AFR_FSDK_FACEMODEL faceFeatureA, AFR_FSDK_FACEMODEL faceFeatureB) {
        FloatByReference fSimilScore = new FloatByReference(0.0f);
        NativeLong ret = AFR_FSDKLibrary.INSTANCE.AFR_FSDK_FacePairMatching(get(), faceFeatureA, faceFeatureB,
                fSimilScore);
//        faceFeatureA.freeUnmanaged();
//        faceFeatureB.freeUnmanaged();
        if (ret.longValue() != 0) {
            System.out.println(String.format("AFR_FSDK_FacePairMatching failed:ret 0x%x", ret.longValue()));
            return 0.0f;
        }
        return fSimilScore.getValue();
    }
}
